<?php
namespace Admin\Controller;
class ConfigController extends AdminController {
    public function index(){
        $configs = $this['Config']->get();
        $page = $this['Config']->getPage();

        $this->assign('lists',$configs);
        $this->assign('page',$page);

        $this->display();
    }

    public function group($group = 0){

        if ( IS_POST ) {
            $res = 1;
            foreach ( $_POST['config'] as $name=>$value) {
                $res &= $this['Config']->where(['name'=>$name])->setField('value',$value);
            }
            // 设置前台提示
            if ($res>0){
                $this->alert['status'] = 1;
                $this->alert['msg'] = '更新成功';
            } else {
                $this->alert['status'] = 0;
                $this->alert['msg'] = '更新失败 '.$this['Config']->getError();
            }
            // 前台提示
            $this->alert();
        }

        // 分组列表
        $groups = C('CONFIG_GROUP_LIST');
        if ( !$title = $groups[$group]) {
            echo '无此分组的配置';
        }
        // 分组标题
        $this->assign('title',$title);

        // 当前分组的配置列表
        $list = $this['Config']->get(['group'=>$group], $field = true, $order = 'sort ASC', $showPage = false);
        $this->assign('list',$list);



        $this->display();
    }

    public function edit($id = null){
        if ( IS_POST ){
            $info = $_POST;
            if ( $id = $this['Config']->update($info) ) {
                // 表单中的id优先
                $info['id'] = $info['id']?:$id;
                // 设置前台提示
                $this->alert['msg'] = '操作成功';
                $this->alert['status'] = 1;
            } else {
                // 设置前台提示
                $this->alert['msg'] = '操作失败 '.$this['Config']->getError();
                $this->alert['status'] = 0;
            }
            // 前台提示
            $this->alert();
        } else {
            if ( $id ){
                $info = $this['Config']->get(['id'=>$id]);
            } else {
                $info = ['status'=>1];
            }
        }

        $this->assign('info',$info);
        $this->display();
    }

    public function delete($id = null){
        $id = array_unique((array)$id);
        $res = $this['Config']->remove($id);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败 '.$this['Config']->getError());
        }
    }

}